from flask import Blueprint, render_template, redirect, url_for, flash
from flask_login import login_required, current_user
from models import db, User

admin_bp = Blueprint('admin', __name__)

@admin_bp.before_request
@login_required
def require_admin():
    if not current_user.is_admin:
        flash('您没有访问该页面的权限', 'danger')
        return redirect(url_for('dashboard'))

@admin_bp.route('/users')
def user_management():
    users = User.query.all()
    return render_template('admin/users.html', users=users)

@admin_bp.route('/promote/<int:user_id>')
def promote_user(user_id):
    user = User.query.get_or_404(user_id)
    user.is_admin = True
    db.session.commit()
    flash(f'已提升 {user.username} 为管理员', 'success')
    return redirect(url_for('admin.user_management'))

@admin_bp.route('/demote/<int:user_id>')
def demote_user(user_id):
    user = User.query.get_or_404(user_id)
    user.is_admin = False
    db.session.commit()
    flash(f'已取消 {user.username} 的管理员权限', 'success')
    return redirect(url_for('admin.user_management'))